/**
 * 未来倒计时模块
 * 负责管理倒计时的添加、查看和更新
 * 倒计时管理模块
 * 负责管理倒计时事件的添加、查看和更新
 */

const { ipcRenderer } = require('electron');
const { handleError, ErrorTypes, tryCatch } = require('../../common/error-handler');

// 模块状态
let countdowns = [];
let updateInterval = null;

/**
 * 初始化倒计时模块
 */
function initialize() {
    console.log('初始化未来倒计时模块...');

    // 加载倒计时数据
    loadCountdowns();

    // 设置事件监听
    setupEventListeners();

    // 初始化页面切换监听
    setupPageNavigation();

    // 设置页面焦点监听
    setupFocusListeners();

    // 开始定时更新
    startUpdates();

    console.log('未来倒计时模块初始化完成');
}

/**
 * 设置页面导航
 */
function setupPageNavigation() {
    // 监听 hashchange 事件
    window.addEventListener('hashchange', handleHashChange);

    // 初始化时检查 hash
    handleHashChange();
}

/**
 * 处理 hash 变化
 */
function handleHashChange() {

}

/**
 * 加载倒计时数据
 */
function loadCountdowns() {
    try {
        const savedCountdowns = localStorage.getItem('countdowns');
        if (savedCountdowns) {
            countdowns = JSON.parse(savedCountdowns);
            updateCountdownsDisplay();
        }
    } catch (error) {
        handleError('加载倒计时数据失败', ErrorTypes.DATA, { error });
    }
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {


    // 添加倒计时按钮
    const addCountdownBtn = document.getElementById('add-countdown-btn');
    if (addCountdownBtn) {
        // 添加点击事件，并防止重复点击
        addCountdownBtn.addEventListener('click', () => {
            //焦点设置到idcountdown-title
            document.getElementById('countdown-title').focus();
            // 禁用按钮，防止重复点击
            addCountdownBtn.disabled = true;
            // 可选：添加视觉反馈
            addCountdownBtn.classList.add('disabled');

            // 显示模态框
            showCountdownModal();

            // 延迟一段时间后重新启用按钮（防止快速连续点击）
            setTimeout(() => {
                addCountdownBtn.disabled = false;
                addCountdownBtn.classList.remove('disabled');
            }, 500); // 500毫秒延迟，可根据需要调整
        });
    }

    // 倒计时编辑模态框
    const countdownModal = document.getElementById('countdown-edit-modal');
    if (countdownModal) {
        // 保存按钮
        const saveBtn = countdownModal.querySelector('#countdown-save-btn');
        if (saveBtn) {
            saveBtn.addEventListener('click', (e) => {
                e.preventDefault();
                // 禁用保存按钮，防止重复点击
                saveBtn.disabled = true;
                // 可选：添加视觉反馈
                saveBtn.classList.add('disabled');

                // 执行保存操作
                saveCountdown();

                // 保存操作完成后，延迟一段时间重新启用按钮
                // 注意：由于saveCountdown函数会隐藏模态框，按钮状态会在下次打开模态框时重置
                // 这里添加延迟是为了防止极端情况下的重复点击
                setTimeout(() => {
                    saveBtn.disabled = false;
                    saveBtn.classList.remove('disabled');
                }, 500);
            });
        }

        // 取消按钮
        const cancelBtn = countdownModal.querySelector('#countdown-cancel-btn');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                hideCountdownModal();
            });
        }

        // 删除按钮
        const deleteBtn = countdownModal.querySelector('#countdown-delete-btn');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => {
                const form = document.getElementById('countdown-form');
                if (form.dataset.countdownId) {
                    deleteCountdown(form.dataset.countdownId);
                }
            });
        }
    }
    //监听卡片点击事件
    const containerCards = document.querySelector('.countdown-cards');
    containerCards.addEventListener('click', (e) => {
        const card = e.target.closest('.countdown-card');
        if (card) {
            const id = card.dataset.id;
            editCountdown(id);
        }
    });

    // 监听表格中编辑按钮的点击事件
    const listContainer = document.querySelector('.countdown-list');
    if (listContainer) {
        const tableBody = listContainer.querySelector('tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                const editBtn = e.target.closest('.edit-countdown-btn');
                if (editBtn) {
                    const id = editBtn.dataset.id;
                    editCountdown(id);
                }
            });
        }
    }

    const cancelButton = document.getElementById('countdown-cancel-btn');
    if (cancelButton) {
        cancelButton.addEventListener('click', () => {
            hideCountdownModal();
        });
    }

}
function editCountdown(id) {
    const countdown = countdowns.find(c => c.id === id);
    if (countdown) {
        showCountdownModal(countdown);
    }
}

// 将editCountdown函数暴露到全局作用域，以便HTML中的onclick属性可以调用它
window.editCountdown = editCountdown;
/**
 * 显示倒计时编辑模态框
 * @param {Object} countdown - 可选，要编辑的倒计时对象
 */
function showCountdownModal(countdown = null) {
    const modal = document.getElementById('countdown-edit-modal');
    const form = document.getElementById('countdown-form');
    document.getElementById('countdown-modal-title').textContent =
        countdown ? '编辑倒计时' : '添加倒计时';
    const deleteButton = document.getElementById('countdown-delete-btn');

    if (modal && form) {
        // 重置表单
        form.reset();
        // 重置表单数据默认当前时间，默认时间为00:00
        document.getElementById('countdown-date').value = formatDateForInput(new Date());
        document.getElementById('countdown-time').value = '00:00';

        // 如果是编辑倒计时，填充表单
        if (countdown) {
            document.getElementById('countdown-title').value = countdown.title;
            document.getElementById('countdown-date').value = formatDateForInput(countdown.date);
            document.getElementById('countdown-time').value = countdown.time || '';
            document.getElementById('countdown-category').value = countdown.category || '其他';
            form.dataset.countdownId = countdown.id;// 将倒计时ID保存到表单数据中
            deleteButton.style.display = 'block';// 显示删除按钮
        } else {
            delete form.dataset.countdownId;
            deleteButton.style.display = 'none';// 隐藏删除按钮
        }

        // 显示模态框
        modal.style.display = 'flex';
    }
}

/**
 * 隐藏倒计时编辑模态框
 */
function hideCountdownModal() {
    const modal = document.getElementById('countdown-edit-modal');
    if (modal) {
        modal.style.display = 'none';
    }
}

/**
 * 保存倒计时
 */
function saveCountdown() {
    console.log('保存倒计时');
    const form = document.getElementById('countdown-form');
    const title = document.getElementById('countdown-title').value;
    const date = document.getElementById('countdown-date').value;
    const time = document.getElementById('countdown-time').value;
    const category = document.getElementById('countdown-category').value;

    if (!title || !date) {
        alert('请填写事件名称和日期');
        return;
    }

    const countdown = {
        id: form.dataset.countdownId || Date.now().toString(),
        title,
        date,
        time,
        category,
        createTime: Date.now()
    };

    // 如果是编辑倒计时，更新现有倒计时
    const countdownIndex = countdowns.findIndex(c => c.id === countdown.id);
    if (countdownIndex !== -1) {
        countdowns[countdownIndex] = { ...countdowns[countdownIndex], ...countdown };
    } else {
        // 否则添加新倒计时
        countdowns.push(countdown);
    }

    // 保存到本地存储
    saveCountdowns();

    // 更新显示
    updateCountdownsDisplay();

    // 隐藏模态框
    hideCountdownModal();
}

/**
 * 删除倒计时
 * @param {string} countdownId - 倒计时ID
 */
function deleteCountdown(countdownId) {
    if (confirm('确定要删除这个倒计时吗？')) {
        countdowns = countdowns.filter(c => c.id !== countdownId);
        saveCountdowns();
        updateCountdownsDisplay();
        hideCountdownModal();
    }
}

/**
 * 保存倒计时到本地存储
 */
function saveCountdowns() {
    try {
        localStorage.setItem('countdowns', JSON.stringify(countdowns));
    } catch (error) {
        handleError('保存倒计时数据失败', ErrorTypes.DATA, { error });
    }
}

/**
 * 更新倒计时显示
 */
function updateCountdownsDisplay() {
    // 更新最近倒计时
    updateNearestCountdown();

    // 更新倒计时列表
    updateCountdownList();
}

/**
 * 更新最近倒计时显示
 */
function updateNearestCountdown() {
    const container = document.getElementById('nearest-countdown');
    if (!container) return;

    // 获取最近的倒计时
    const now = Date.now();
    const futureCountdowns = countdowns
        .filter(c => {
            const timestamp = new Date(`${c.date}T${c.time || '00:00'}`).getTime();
            return timestamp > now;
        })
        .sort((a, b) => {
            const timestampA = new Date(`${a.date}T${a.time || '00:00'}`).getTime();
            const timestampB = new Date(`${b.date}T${b.time || '00:00'}`).getTime();
            return timestampA - timestampB;
        });

    if (futureCountdowns.length === 0) {
        container.innerHTML = `
            <div class="countdown-empty">
                <i class="fas fa-hourglass-end"></i>
                <p>暂无倒计时</p>
            </div>
        `;
        return;
    }

    const nearest = futureCountdowns[0];
    const timestamp = new Date(`${nearest.date}T${nearest.time || '00:00'}`).getTime();
    const timeLeft = calculateTimeLeft(nearest.date, nearest.time);
    container.innerHTML = `
                    <div class="countdown-card" data-id="${nearest.id}" data-category="${nearest.category}">
                        <div class="countdown-header">
                            <div class="countdown-title">${nearest.title}</div>
                            <div class="countdown-category">${nearest.category}</div>
                        </div>
                        <div class="countdown-time">
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.days}</div>
                                <div class="countdown-label">天</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.hours}</div>
                                <div class="countdown-label">时</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.minutes}</div>
                                <div class="countdown-label">分</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.seconds}</div>
                                <div class="countdown-label">秒</div>
                            </div>
                        </div>
                        <div class="countdown-target">
                            目标时间: ${nearest.date} ${nearest.time}
                        </div>
                    </div>
                `;
}

/**
 * 更新倒计时列表
 */
function updateCountdownList() {
    const container = document.querySelector('.countdown-cards');
    if (!container) return;

    if (countdowns.length === 0) {
        container.innerHTML = `
            <div class="countdown-empty">
                <i class="fas fa-hourglass-end"></i>
                <p>暂无倒计时</p>
            </div>
        `;
        return;
    }
    // 按目标日期排序
    const sortedCountdowns = [...countdowns].sort((a, b) => {
        const dateA = new Date(`${a.date}T${a.time}`);
        const dateB = new Date(`${b.date}T${b.time}`);
        return dateA - dateB;
    });

    const now = Date.now();
    const activeCountdowns = [];
    const expiredCountdowns = [];

    sortedCountdowns.forEach(countdown => {
        const targetDate = new Date(`${countdown.date}T${countdown.time}`);
        if (targetDate > now) {
            activeCountdowns.push(countdown);
        } else {
            expiredCountdowns.push(countdown);
        }
    });
    container.innerHTML = activeCountdowns
        .sort((a, b) => {
            const timestampA = new Date(`${a.date}T${a.time || '00:00'}`).getTime();
            const timestampB = new Date(`${b.date}T${b.time || '00:00'}`).getTime();
            return timestampA - timestampB;
        })
        .slice(0, 6)// 只显示前6个
        .map(countdown => {
            const timestamp = new Date(`${countdown.date}T${countdown.time || '00:00'}`).getTime();
            const timeLeft = calculateTimeLeft(countdown.date, countdown.time);
            const isExpired = timestamp <= now;

            return `
                    <div class="countdown-card" data-id="${countdown.id}" data-category="${countdown.category}">
                        <div class="countdown-header">
                            <div class="countdown-title">${countdown.title}</div>
                            <div class="countdown-category">${countdown.category}</div>
                        </div>
                        <div class="countdown-time">
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.days}</div>
                                <div class="countdown-label">天</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.hours}</div>
                                <div class="countdown-label">时</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.minutes}</div>
                                <div class="countdown-label">分</div>
                            </div>
                            <div class="countdown-unit">
                                <div class="countdown-value">${timeLeft.seconds}</div>
                                <div class="countdown-label">秒</div>
                            </div>
                        </div>
                        <div class="countdown-target">
                            目标时间: ${countdown.date} ${countdown.time}
                        </div>
                    </div>
                `;
        })
        .join('');

    // 渲染完整列表（包括所有倒计时）
    const listContainer = document.querySelector('.countdown-list');
    const tableBody = listContainer.querySelector('tbody');
    const emptyState = listContainer.querySelector('.countdown-list-empty-state');

    if (countdowns.length === 0) {
        tableBody.innerHTML = '';
        emptyState.style.display = 'flex';
    } else {
        emptyState.style.display = 'none';
        const allCountdowns = [...activeCountdowns, ...expiredCountdowns];
        tableBody.innerHTML = allCountdowns.map(countdown => {
            const timestamp = new Date(`${countdown.date}T${countdown.time || '00:00'}`).getTime();
            const timeLeft = calculateTimeLeft(countdown.date, countdown.time);
            const isExpired = timeLeft.expired;
            const timeLeftText = isExpired ? '已过期' :
                `${timeLeft.days}天${timeLeft.hours}时${timeLeft.minutes}分`;

            return `
                    <tr class="${isExpired ? 'expired' : ''}" data-id="${countdown.id}">
                        <td>${countdown.title}</td>
                        <td>${countdown.category}</td>
                        <td>${countdown.date} ${countdown.time}</td>
                        <td>${timeLeftText}</td>
                        <td>${isExpired ? '<span class="badge badge-danger">已过期</span>' :
                    '<span class="badge badge-success">进行中</span>'}</td>
                        <td class="countdown-actions">
                            <button class="edit-countdown-btn" data-id="${countdown.id}">
                                <i class="fas fa-edit"></i>
                            </button>
                        </td>
                    </tr>
                `;
        }).join('');
    }
}

/**
 * 开始定时更新
 */
function startUpdates() {
    // 每秒更新一次
    updateInterval = setInterval(() => {
        updateCountdownsDisplay();
    }, 1000);
}

/**
 * 停止定时更新
 */
function stopUpdates() {
    if (updateInterval) {
        clearInterval(updateInterval);
        updateInterval = null;
    }
}

/**
 * 设置页面焦点监听器
 */
function setupFocusListeners() {
    // 当页面失去焦点时暂停更新
    window.addEventListener('blur', pauseUpdates);

    // 当页面获得焦点时恢复更新
    window.addEventListener('focus', resumeUpdates);

    // 当页面可见性改变时处理
    document.addEventListener('visibilitychange', handleVisibilityChange);

    console.log('页面焦点监听器设置完成');
}

/**
 * 处理页面可见性变化
 */
function handleVisibilityChange() {
    if (document.hidden) {
        pauseUpdates();
    } else {
        resumeUpdates();
    }
}

/**
 * 暂停倒计时更新
 */
function pauseUpdates() {
    console.log('页面失去焦点，暂停倒计时更新');
    stopUpdates();
}

/**
 * 恢复倒计时更新
 */
function resumeUpdates() {
    console.log('页面获得焦点，恢复倒计时更新');
    // 先更新一次显示
    updateCountdownsDisplay();
    // 然后重新开始定时更新
    startUpdates();
}

/**
 * 计算剩余时间
 * @param {number} timestamp - 目标时间戳
 * @returns {Object} 剩余时间对象
 */
function calculateTimeLeft(targetDate, targetTime) {
    const target = new Date(`${targetDate}T${targetTime}`);
    const now = new Date();
    const diff = target - now;

    if (diff <= 0) {
        return { days: 0, hours: 0, minutes: 0, seconds: 0, expired: true };
    }

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return { days, hours, minutes, seconds, expired: false };
}

/**
 * 格式化日期
 * @param {number} timestamp - 时间戳
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(timestamp) {
    return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    });
}

/**
 * 格式化日期为输入框格式
 * @param {string} date - 日期字符串
 * @returns {string} 格式化后的日期字符串
 */
function formatDateForInput(date) {
    return new Date(date).toISOString().split('T')[0];
}

/**
 * 导航到倒计时页面
 */
function navigateToCountdown() {
    const countdownPage = document.querySelector('.page[data-page="countdown"]');
    if (countdownPage) {
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });
        countdownPage.classList.add('active');
        window.location.hash = '#countdown';
        updateCountdownsDisplay();
    }
}

/**
 * 清理倒计时模块资源
 * 在模块卸载时调用，移除事件监听器并停止更新
 */
function cleanup() {
    console.log('清理倒计时模块资源...');

    // 停止定时更新
    stopUpdates();

    // 移除焦点事件监听器
    window.removeEventListener('blur', pauseUpdates);
    window.removeEventListener('focus', resumeUpdates);
    document.removeEventListener('visibilitychange', handleVisibilityChange);

    // 移除hashchange事件监听
    window.removeEventListener('hashchange', handleHashChange);

    console.log('倒计时模块资源清理完成');
}

// 导出模块
module.exports = {
    initialize,
    loadCountdowns,
    showCountdownModal,
    hideCountdownModal,
    saveCountdown,
    deleteCountdown,
    updateCountdownsDisplay,
    stopUpdates,
    pauseUpdates,
    resumeUpdates,
    cleanup,
    editCountdown
};